import { ModelConfigInfo, ConfigEvent, ConfigEventType } from '@/types/model-config';
import { EventEmitter } from '@/utils/event-emitter';

export interface ConfigChangeListener {
  (event: ConfigEvent): void;
}

export interface SyncStatus {
  syncing: boolean;
  lastSyncTime?: Date;
  pendingChanges: number;
  error?: string;
}

class ConfigSyncService extends EventEmitter {
  private syncInterval: number | null = null;
  private syncStatus: SyncStatus = {
    syncing: false,
    pendingChanges: 0
  };
  private pendingEvents: ConfigEvent[] = [];
  private websocket: WebSocket | null = null;
  private reconnectAttempts = 0;
  private maxReconnectAttempts = 5;
  private reconnectDelay = 1000;

  constructor() {
    super();
    this.setMaxListeners(100); // 支持多个监听器
  }

  /**
   * 启动配置同步服务
   */
  startSync() {
    // 启动WebSocket连接用于实时同步
    this.connectWebSocket();

    // 启动定期同步任务
    this.startPeriodicSync();

    // 监听存储变化（用于跨标签页同步）
    this.listenStorageChanges();
  }

  /**
   * 停止配置同步服务
   */
  stopSync() {
    if (this.syncInterval) {
      clearInterval(this.syncInterval);
      this.syncInterval = null;
    }

    if (this.websocket) {
      this.websocket.close();
      this.websocket = null;
    }

    window.removeEventListener('storage', this.handleStorageChange);
  }

  /**
   * 连接WebSocket用于实时同步
   */
  private connectWebSocket() {
    const wsUrl = import.meta.env.VITE_WS_URL || import.meta.env.REACT_APP_WS_URL || 'ws://localhost:8002';
    const fullUrl = wsUrl.includes('/ws/config-sync') ? wsUrl : `${wsUrl}/ws/config-sync`;
    
    try {
      this.websocket = new WebSocket(fullUrl);

      this.websocket.onopen = () => {
        console.log('ConfigSync WebSocket connected');
        this.reconnectAttempts = 0;
        this.emit('connected');
        
        // 发送认证信息
        this.websocket?.send(JSON.stringify({
          type: 'auth',
          token: this.getToken()
        }));

        // 同步待处理的事件
        this.flushPendingEvents();
      };

      this.websocket.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          this.handleRemoteConfigChange(data);
        } catch (error) {
          console.error('Failed to parse WebSocket message:', error);
        }
      };

      this.websocket.onerror = (error) => {
        console.error('WebSocket error:', error);
        this.emit('error', error);
      };

      this.websocket.onclose = () => {
        console.log('WebSocket disconnected');
        this.emit('disconnected');
        this.attemptReconnect();
      };

    } catch (error) {
      console.error('Failed to create WebSocket connection:', error);
      this.attemptReconnect();
    }
  }

  /**
   * 尝试重新连接WebSocket
   */
  private attemptReconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('Max reconnection attempts reached');
      this.emit('reconnect-failed');
      return;
    }

    this.reconnectAttempts++;
    const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);

    console.log(`Attempting to reconnect in ${delay}ms (attempt ${this.reconnectAttempts})`);

    setTimeout(() => {
      this.connectWebSocket();
    }, delay);
  }

  /**
   * 启动定期同步任务
   */
  private startPeriodicSync() {
    // 每5分钟同步一次
    this.syncInterval = window.setInterval(() => {
      this.performSync();
    }, 5 * 60 * 1000);

    // 立即执行一次同步
    this.performSync();
  }

  /**
   * 执行配置同步
   */
  private async performSync() {
    if (this.syncStatus.syncing) {
      console.log('Sync already in progress');
      return;
    }

    this.syncStatus.syncing = true;
    this.emit('sync-start');

    try {
      // 获取本地配置
      const localConfigs = this.getLocalConfigs();
      
      // 获取远程配置
      const remoteConfigs = await this.fetchRemoteConfigs();
      
      // 合并配置
      const mergedConfigs = this.mergeConfigs(localConfigs, remoteConfigs);
      
      // 保存合并后的配置
      this.saveLocalConfigs(mergedConfigs);

      // 如果有待处理的事件，发送到服务器
      if (this.pendingEvents.length > 0) {
        await this.sendPendingEvents();
      }

      this.syncStatus.syncing = false;
      this.syncStatus.lastSyncTime = new Date();
      this.syncStatus.pendingChanges = 0;

      const result = {
        success: true,
        syncedAt: new Date(),
        configCount: mergedConfigs.length
      };

      this.emit('sync-complete', result);

    } catch (error) {
      this.syncStatus.syncing = false;
      this.syncStatus.error = error instanceof Error ? error.message : String(error);
      this.emit('sync-error', error);
    }
  }

  /**
   * 监听存储变化（跨标签页同步）
   */
  private listenStorageChanges() {
    window.addEventListener('storage', this.handleStorageChange);
  }

  /**
   * 处理存储变化事件
   */
  private handleStorageChange = (event: StorageEvent) => {
    if (event.key === 'model_configs' && event.newValue) {
      try {
        const configs = JSON.parse(event.newValue);
        // 触发配置变更事件
        configs.forEach((config: ModelConfigInfo) => {
          const change: ConfigEvent = {
            type: ConfigEventType.UPDATED,
            configId: config.id!,
            changes: config,
            timestamp: new Date()
          };
          this.emit('config-changed', change);
        });
      } catch (error) {
        console.error('Failed to parse storage change:', error);
      }
    }
  };

  /**
   * 处理远程配置变更
   */
  private handleRemoteConfigChange(data: any) {
    const event: ConfigEvent = {
      type: data.type || ConfigEventType.UPDATED,
      configId: data.configId,
      changes: data.config,
      timestamp: new Date(data.timestamp || Date.now())
    };

    // 更新本地存储
    if (event.changes) {
      this.updateLocalConfig(event.changes as ModelConfigInfo);
    }

    // 触发事件
    this.emit('config-changed', event);
  }

  /**
   * 发送待处理的事件
   */
  private async sendPendingEvents() {
    if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) {
      return;
    }

    while (this.pendingEvents.length > 0) {
      const event = this.pendingEvents.shift()!;
      this.websocket.send(JSON.stringify(event));
    }
  }

  /**
   * 刷新待处理事件
   */
  private flushPendingEvents() {
    this.sendPendingEvents();
  }

  /**
   * 获取本地配置
   */
  private getLocalConfigs(): ModelConfigInfo[] {
    const stored = localStorage.getItem('model_configs');
    return stored ? JSON.parse(stored) : [];
  }

  /**
   * 保存本地配置
   */
  private saveLocalConfigs(configs: ModelConfigInfo[]) {
    localStorage.setItem('model_configs', JSON.stringify(configs));
  }

  /**
   * 更新单个本地配置
   */
  private updateLocalConfig(config: ModelConfigInfo) {
    const configs = this.getLocalConfigs();
    const index = configs.findIndex(c => c.id === config.id);
    
    if (index !== -1) {
      configs[index] = config;
    } else {
      configs.push(config);
    }
    
    this.saveLocalConfigs(configs);
  }

  /**
   * 获取远程配置
   */
  private async fetchRemoteConfigs(): Promise<ModelConfigInfo[]> {
    // TODO: 实现从服务器获取配置
    return [];
  }

  /**
   * 合并本地和远程配置
   */
  private mergeConfigs(local: ModelConfigInfo[], remote: ModelConfigInfo[]): ModelConfigInfo[] {
    const merged = [...local];
    
    remote.forEach(remoteConfig => {
      const localIndex = merged.findIndex(c => c.id === remoteConfig.id);
      
      if (localIndex === -1) {
        // 远程配置不存在于本地，添加
        merged.push(remoteConfig);
      } else {
        // 比较时间戳，保留最新的
        const localConfig = merged[localIndex];
        const localTime = new Date(localConfig.lastModified || 0).getTime();
        const remoteTime = new Date(remoteConfig.lastModified || 0).getTime();
        
        if (remoteTime > localTime) {
          merged[localIndex] = remoteConfig;
        }
      }
    });
    
    return merged;
  }

  /**
   * 获取认证令牌
   */
  private getToken(): string {
    return localStorage.getItem('authToken') || '';
  }

  /**
   * 触发配置变更事件
   */
  triggerConfigChange(event: ConfigEvent) {
    // 添加到待处理队列
    this.pendingEvents.push(event);
    this.syncStatus.pendingChanges++;

    // 如果WebSocket连接正常，立即发送
    if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
      this.sendPendingEvents();
    }

    // 触发本地事件
    this.emit('config-changed', event);
  }

  /**
   * 获取同步状态
   */
  getSyncStatus(): SyncStatus {
    return { ...this.syncStatus };
  }

  /**
   * 强制同步
   */
  forceSync() {
    return this.performSync();
  }

  /**
   * 监听配置变更
   */
  onConfigChange(listener: ConfigChangeListener) {
    this.on('config-changed', listener);
    return () => this.off('config-changed', listener);
  }

  /**
   * 监听同步事件
   */
  onSyncEvent(event: string, listener: Function) {
    this.on(event, listener);
    return () => this.off(event, listener);
  }
}

// 导出单例
const configSyncService = new ConfigSyncService();
export default configSyncService;